<template>
  <el-card style="margin: 20px 0 0 20px">
    <div>
      <el-input v-model="randbs" style="width: 180px;margin-right: 20px" placeholder="请输入用户名" />
      <el-button type="primary" icon="el-icon-search" size="small" @click="inquireUserAdmin">查询</el-button>
      <el-button style="color: black" type="info" size="small" icon="el-icon-delete" @click="randbs=''">清空</el-button>
    </div>
    <div style="margin-top: 20px">
      <el-button v-has="'btn.User.add'" type="primary" @click="isDialog">添加</el-button>
      <el-button v-has="'btn.User.remove'" style="background-color: pink;border-color: pink" type="info" @click="deleteUserAdminList">批量删除</el-button>
    </div>
    <!-- 表单数据 -->
    <el-table
      ref="multipleTable"
      :data="userAdminList"
      border
      tooltip-effect="dark"
      style="width: 100%;margin-top: 20px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="序号"
        type="index"
        width="55"
      />
      <el-table-column
        prop="username"
        label="用户名"
        width="120"
      />
      <el-table-column
        prop="nickName"
        label="用户名称"
        width="120"
      />
      <el-table-column
        prop="roleName"
        label="角色列表"
        show-overflow-tooltip
      />
      <el-table-column
        prop="gmtCreate"
        label="创建时间"
        show-overflow-tooltip
      />
      <el-table-column
        prop="gmtModified"
        label="更新时间"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        width="200"
      >
        <template #default="{row}">
          <el-button v-has="'btn.User.assgin'" title="查看角色信息" size="small" type="info" icon="el-icon-user-solid" @click="isRoleDialog(row)" />
          <el-button v-has="'btn.User.update'" title="修改用户信息" size="small" type="primary" icon="el-icon-edit-outline" @click="isDialog(row)" />
          <el-button v-has="'btn.User.remove'" title="删除用户" size="small" type="danger" icon="el-icon-delete" @click="deleteUserAdminItem(row.id)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      style="margin-top: 10px"
      :pager-count="5"
      :current-page="page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @current-change="changePage"
      @size-change="changeLimit"
    />
    <!-- 添加修改对话框 -->
    <el-dialog
      :title=" ruleForm.username? '修改用户':'添加用户'"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <!-- 表单数据 -->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="ruleForm.nickName" />
        </el-form-item>
        <el-form-item v-if="isHiden" label="用户密码" prop="password">
          <el-input v-model="ruleForm.password" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAndUpDateUserItem">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="设置角色"
      :visible.sync="roleDialogVisible"
      width="50%"
    >
      <el-form ref="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userName" disabled />
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group v-model="checkedList" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in allRolesList" :key="item.id" :label="item.roleName" />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeRoleDialog">取 消</el-button>
        <el-button type="primary" @click="allocationRole">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  reqAddUserAdminItemAsync,
  reqDeleteUserAdminItemAsync, reqDeleteUserAdminListAsync, reqGetUserAdminRoleAsync, reqPostUserAdminRoleAsync,
  reqUpdateUserAdminItemAsync,
  reqUserAdminAsync
} from '@/api/userAdmin'

export default {
  name: 'User',
  data() {
    return {
      page: 1, // 初始页数
      limit: 5, // 初始每页条数
      total: 10, // 初始总条数
      userAdminList: [], // 初始所有的用户的信息
      dialogVisible: false, // 控制对话框的显示隐藏
      ruleForm: { // 收集添加/修改的数据
        username: '',
        nickName: '',
        password: ''
      },
      rules: { // 表单校验规则
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      isHiden: false, // 初始添加/修改功能密码框默认不显示
      randbs: '', // 初始的查询参数
      checkedIdAll: [], // 收集所有选中的平台用户角色信息的id
      roleDialogVisible: false, // 控制分配角色的对话框显示隐藏
      allRolesList: [], // 保存当前平台用户所有可以分配的角色
      assignRoles: [], // 保存当前平台用户已经分配好的角色信息
      checkedList: [], // 用来保存当前平台用户选中的角色
      checkAll: false, // 全选是否选中状态
      isIndeterminate: false, // 全选 - 状态
      userName: '', // 保存用户名
      userid: 0 // 用户id
    }
  },
  mounted() {
    this.getUserAdminList()
  },
  methods: {
    // 获取平台所有的用户信息
    async getUserAdminList() {
      try {
        const result = await reqUserAdminAsync(this.page, this.limit, this.randbs)
        this.userAdminList = result.data.items
        this.total = result.data.total
      } catch (e) {
        this.$message.error('获取平台用户信息失败')
      }
    },
    // 页码的改变
    changePage(currentPage) {
      this.page = currentPage
      // 更新平台用户数据
      this.getUserAdminList()
    },
    // 每页条数的改变
    changeLimit(currentLimit) {
      this.limit = currentLimit
      // 更新平台用户数据
      this.getUserAdminList()
    },
    // 点击显示对话框
    isDialog(row = {}) {
      this.$refs['ruleForm']?.clearValidate()
      // 显示对话框
      this.dialogVisible = true
      if (row.username) { // 代表修改进来的
        this.ruleForm = { ...row }
        // 关闭密码框显示
        this.isHiden = false
      } else { // 代表添加进来的
        // 清空上一次的添加的数据
        this.ruleForm = {
          username: '',
          nickName: '',
          password: ''
        }
        // 开启密码框显示
        this.isHiden = true
      }
    },
    // 添加或者修改
    async addAndUpDateUserItem() {
      // 表单的整体校验
      await this.$refs['ruleForm'].validate(async(valid) => {
        if (!valid) { // 校验失败
          return false
        } else { // 校验成功
          try {
            if (this.ruleForm.id) {
              await reqUpdateUserAdminItemAsync(this.ruleForm)
              this.$message.success('修改成功')
              // 更新平台用户数据
              await this.getUserAdminList()
            } else {
              await reqAddUserAdminItemAsync(this.ruleForm)
              this.$message.success('添加成功')
              // 更新平台用户数据
              await this.getUserAdminList()
            }
          } catch (e) {
            this.$message.error(this.ruleForm.id ? '修改失败' : `添加失败用户名重复`)
          }
          // 关闭对话框
          this.dialogVisible = false
          // 关闭密码框显示
          this.isHiden = false
        }
      })
    },
    // 点击查询数据
    async inquireUserAdmin() {
      try {
        const result = await reqUserAdminAsync(this.page, this.limit, this.randbs)
        this.userAdminList = result.data.items
        this.total = result.data.total
      } catch (e) {
        this.$message.error('获取平台用户信息失败')
      }
    },
    // 删除单个平台用户信息
    async deleteUserAdminItem(id) {
      try {
        await reqDeleteUserAdminItemAsync(id)
        this.$message.success('删除单个成功')
        // 更新数据
        await this.getUserAdminList()
      } catch (e) {
        this.$message.error('删除单个失败')
      }
    },
    // 收集所有选中的数据
    handleSelectionChange(checkedAll) {
      this.checkedIdAll = checkedAll.map(item => item.id)
    },
    // 删除多个平台用户信息
    async deleteUserAdminList() {
      try {
        await reqDeleteUserAdminListAsync(this.checkedIdAll)
        this.$message.success('删除多个成功')
        // 更新数据
        await this.getUserAdminList()
      } catch (e) {
        this.$message.error('删除多个失败')
      }
    },
    // 控制设置平台用户信息角色的弹窗显示
    async isRoleDialog(row) {
      // 显示对话框
      this.roleDialogVisible = true
      // 保存用户名
      this.userName = row.username
      // 保存用户id
      this.userid = row.id
      try {
        // 获取该用户的角色信息
        const result = await reqGetUserAdminRoleAsync(row.id)
        this.allRolesList = result.data.allRolesList // 保存当前平台用户所有可以分配的角色
        this.assignRoles = result.data.assignRoles // 保存当前平台用户已经分配好的角色信息
        this.checkedList = this.assignRoles.map(item => item.roleName) // 用来保存当前平台用户选中的角色
        this.isIndeterminate = this.checkedList.length > 0
      } catch (e) {
        this.$message.error('获取角色信息失败')
      }
    },
    // 关闭角色对话框
    closeRoleDialog() {
      // 关闭对话框
      this.roleDialogVisible = false
      // 重置所有数据
      this.allRolesList = []
      this.assignRoles = []
      this.checkAll = false
      this.isIndeterminate = false
    },
    // 全选功能
    handleCheckAllChange(val) {
      this.checkedList = val ? this.allRolesList.map(item => item.roleName) : []
      this.isIndeterminate = false
    },
    // 控制全选按钮的 - 状态
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.allRolesList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allRolesList.length
    },
    // 角色分配功能
    async allocationRole() {
      // 获取分配的角色id
      this.checkedIdAll = this.allRolesList.filter(item => { // 返回选中的角色数据
        for (const itemKey in this.checkedList) {
          if (this.checkedList[itemKey] === item.roleName) {
            return item
          }
        }
      }).map(items => items.id) // 选中的角色数据映射出对应id
      try {
        await reqPostUserAdminRoleAsync(this.userid, this.checkedIdAll)
        this.$message.success('分配成功')
        // 更新数据
        await this.getUserAdminList()
      } catch (e) {
        this.$message.error('分配失败')
      }
      // 关闭对话框
      this.roleDialogVisible = false
    }
  }
}
</script>

<style scoped>
</style>
